﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Office.Interop.Excel;
using HuoTu.Common;
namespace DomainSearchTools.Common
{
    public class DomainFileHelper
    {
        public bool SaveToFile(List<string> list, ExportFileType fileType, string filename, ref string error)
        {
            bool result = false;
            StringBuilder strB = new StringBuilder();
            try
            {
                if (fileType == ExportFileType.TXT)//txt
                {
                    foreach (var item in list)
                    {
                        strB.AppendFormat(@"{0}
", item);
                    }
                    SysFile.WriteFile(filename, strB.ToString());
                    result = true;
                }
                else if (fileType == ExportFileType.XLS)//xls
                {
                    Application excel = new Application();
                    if (excel == null)
                    {
                        error = "无法启动Excel，可能您的机子未安装Excel";
                        return false;
                    }

                    try
                    {
                        excel.Application.Workbooks.Add(true);
                        excel.Visible = false;
                      
                        Worksheet worksheet = (Worksheet)excel.ActiveSheet;
                        /*合并标题单元格*/
                        //worksheet.get_Range(worksheet.Cells[1, 1] as Range, worksheet.Cells[RowCount,1] as Range).Merge();

                        int i = 1;
                        foreach (var text in list)
                        {
                            excel.Cells[i, 1] = text;
                            i++;
                        }

                        worksheet.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing
                            , Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);  
                        result = true;

                    }
                    catch (Exception ex)
                    {
                        error = "导出文件时出错,文件可能正被打开！" + ex.Message;
                        return false;
                    }
                    finally
                    {
                        excel.Quit();
                    }
                }
            }
            catch { }
            return result;
        }
    }
}
